package com.sanbi.erp.api.util;

import com.sanbi.erp.db.config.BizException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Desc:
 * @Data: 2022/7/21 15:53
 * @Author: jxk
 */
@Slf4j
public class OkHttpUtil {

   private static final OkHttpClient okHttpClient=new OkHttpClient();


    /**
     * get
     * @param url   请求的url
     * @param param 请求的参数
     * @return
     */
    public static  String get(String url, Map<String, String> param) throws IOException {

        StringBuffer sb = new StringBuffer(url);
        if (param!= null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        Response response = null;

            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();

        }
        return String.valueOf(status);
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
//    public static String post(String url, Map<String,String> params) {
//        String bizContent = params.get("bizContent");
////        String s = bizContent + JTExpressConfig.privateKey;
////        log.info("签名前的字符串：{}",s);
////        String digest = Base64Util.encode2(MD5Util.md(s));
////        log.info("签名后的字符串：{}",digest);
//        String digest = JTExpressUtil.createDigest(bizContent);
//
//        FormBody.Builder builder = new FormBody.Builder();
//        //添加参数
//        if (params != null && params.keySet().size() > 0) {
//            for (String key : params.keySet()) {
//
//                builder.add(key, params.get(key));
//            }
//        }
//        assert digest != null;
//        Request request = new Request.Builder()
//                .addHeader("content-type", "application/x-www-form-urlencoded")
//                .addHeader("apiAccount", JTExpressConfig.apiAccount)
//                .addHeader("digest", digest)
//                .addHeader("timestamp",JTExpressConfig.timestamp)
//                .addHeader("timezone",JTExpressConfig.timeZone)
//                .url(url)
//                .post(builder.build())
//                .build();
//        Response response = null;
//        try {
//            response = okHttpClient.newCall(request).execute();
//            int status = response.code();
//            log.info("状态码:"+status);
//            if (response.isSuccessful()) {
//                return response.body().string();
//            }
//        } catch (IOException e) {
//            log.error("okhttp3 post exception：{}", e.getMessage());
//        }
//        return String.valueOf(response.code());
//    }

    /**
     * get
     * @param url     请求的url
     * @param param 请求的参数
     * @return
     */
    public static String getForHeader(String url, Map<String, String> param) throws IOException {
        StringBuffer sb = new StringBuffer(url);
        if (param != null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .addHeader("key", "value")
                .url(sb.toString())
                .build();
        Response response = null;

            response =okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        return String.valueOf(status);
    }

    /**
     * Post请求发送JSON数据
     * @param url 请求Url
     * @param jsonParams 请求的JSON
     */
    public static String postJsonParams(String url, String jsonParams) {
//        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .build();
        int status=0;
        try {
            response = client.newCall(request).execute();
            status = response.code();
            log.info("状态码:"+status);
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        }
        throw new BizException(status,"okhttp3 post exception");
    }

    /**
     * Post请求发送JSON数据
     * @param url 请求Url
     * @param jsonParams 请求的JSON
     */
//    public static String postJsonParams2(String url, String jsonParams) {
////        String responseBody = "";
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), jsonParams);
//        Request request = new Request.Builder()
//                .addHeader("apiAccount", JTExpressConfig.apiAccount)
//                .addHeader("digest", Objects.requireNonNull(Base64Util.encode(MD5Util.MD5(jsonParams + JTExpressConfig.privateKey))))
//                .addHeader("timestamp",JTExpressConfig.timestamp)
//                .addHeader("timezone",JTExpressConfig.timeZone)
//                .url(url)
//                .post(requestBody)
//                .build();
//
//        Response response = null;
//        try {
//            response = okHttpClient.newCall(request).execute();
//            int status = response.code();
//            log.info("状态码:"+status);
//            if (response.isSuccessful()) {
//                return response.body().string();
//            }
//        } catch (IOException e) {
//            log.error("okhttp3 post exception：{}", e.getMessage());
//        }
//        return String.valueOf(response.code());
//
//    }

    /**
     * Post请求发送xml类型数据
     * @param url 请求Url
     * @param xml 请求的xml
     */
    public static String postXmlParams(String url, String xml) {
        String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * 上传pdf文件
     * @param url
     * @param fileName
     * @return
     */
    public static String postPDF(String url,String fileName){

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/pdf"), new File(fileName));
        MultipartBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file","merge.pdf",requestBody)
                .build();
        Request request = new Request.Builder()
                .header("Content-Type","mutipart/from-data")
                .post(body)
                .url(url)
                .build();
        OkHttpClient client= new OkHttpClient.Builder().build();
        int code=0;
        try {
            Response response = client.newCall(request).execute();
            code = response.code();
            if (response.isSuccessful()){
                String resp = response.body().string();
                return resp;
            }
        } catch (IOException e) {
          log.error("调用上传服务失败",e);
        }
        throw new BizException(code,"调用上传服务失败");
    }

}
